<template>
    <div class="vue-container">
        <div class="icif-info">
          <div class="icif-img" v-if="credit.PayPic!=null"><img :src="credit.PayPic"></div>
          <div class="icif-content">
            <h3>
              {{credit.Theme}}
            </h3>
            <p v-if="credit.ThemeTime!=null"><van-icon name="clock" />{{credit.ThemeTime}}</p>
            <p v-if="credit.Adress!=null"><van-icon name="location" />{{credit.Adress}}</p>
          </div>
        </div>
        <van-cell-group>
            <van-field
                v-model="userInfo.Name"
                required
                label="姓名"
                placeholder="请输入真实姓名"
                input-align="right"
            />
            <van-field
                v-model="userInfo.Phone"
                type="tel"
                label="手机号"
                placeholder="请输入手机号"
                required
                input-align="right"
            />
              <van-field
              v-show="codeIsShow==true&&userInfo.Phone!=phone"
              v-model="userInfo.VerifyVode"
              required
              center
              clearable
              label="验证码"
              input-align="right"
              placeholder="请输入验证码"
            >
            <van-button slot="button" size="small" type="primary" :disabled="btnDisabled" @click="getCode">{{btnText}}</van-button>
            </van-field>
            <van-field
                v-model="userInfo.Company"
                required
                label="公司"
                placeholder="请输入单位名称"
                input-align="right"
                @blur="isChecked=true"
            />
            <div class="company-tips" v-if="companyTips.length>0&&isChecked==false">
              <div class="tips-item" v-for="(item,index) in companyTips" :key="index" @click="getCompany(item)">{{item.corpname}}</div>
            </div>
            <div class="match-making" v-if="userInfo.ST!='dmz1017'">
              <van-cell title="是否参加对接洽谈" required>
                    <van-radio-group v-model="userInfo.IsMatchMaking">
                        <van-radio :name="true">是</van-radio>
                        <van-radio :name="false">否</van-radio>
                    </van-radio-group>
                </van-cell>
            </div>
            <van-field
                v-if="userInfo.ST!='dmz1017'"
                v-model="userInfo.Post"
                required
                label="职务"
                placeholder="请输入职务"
                input-align="right"
            />
            <van-field
                  v-if="userInfo.ST!='dmz1017'"
                  v-model="userInfo.CertificateType"
                  required
                  label="证件类别"
                  input-align="right"
                  placeholder="请选择证件类别"
                  readonly
                  icon="arrow"
                  @click-icon="showCertiPicker"
                  @click="showCertiPicker"
              />
              <van-field
                v-if="userInfo.ST!='dmz1017'"
                v-model="userInfo.IDCard"
                required
                label="证件号"
                placeholder="请输入证件号"
                input-align="right"
            />
            <div class="file-image" v-if="userInfo.ST!='dmz1017'">
              <van-cell title="上传证件照(免冠纯底色正脸照)" is-link required value="点击上传" @click="showFileModel">
                    <img id="img" class="preview-image" v-if="userInfo.HeadImage!=''" :src="userInfo.HeadImage"  @click="previewImg">
                </van-cell>
            </div>            
        </van-cell-group>
        <div class="submit-btn">
            <van-button size="large" type="primary" @click="submitForm">提交</van-button>
        </div>
        
        <!-- 选择证件类型 -->
            <van-popup v-model="certificatePicker">
                <div class="certi-picker">
                    <van-cell-group>
                    <van-cell v-for="(item,index) in certificateList" :key="index" :title="item.text" clickable @click="certiTypePicker(item)" />
                </van-cell-group>
                </div>  
            </van-popup>
            <!-- 上传图片 -->
        <van-actionsheet v-model="fileModel">
                <div class="actionsheet-title">请上传证件照</div>
                <div class="actionsheet-row">
                    <span>从相册中选择</span>
                    <input type="file" accept="image/*" @change="fileChange">
                </div>
                <div class="actionsheet-row">
                    <span>拍照</span>
                    <input type="file" capture="camera" accept="image/*" @change="fileChange">
                </div>
                <div class="actionsheet-close" @click="fileToggle(0)">取消</div>
            </van-actionsheet>    
    </div>
</template>

<script>
import axios from "axios";
import { ImagePreview } from "vant";
export default {
  name: "entryPage",
  data() {
    return {
      certificatePicker: false,
      fileModel: false,
      codeIsShow: false,
      credit: {},
      btnText: "发送验证码",
      btnDisabled: false,
      phone: "",
      companyTips: [],
      isChecked: true,
      userInfo: {
        InviterUnionId: "",
        UserAgent: "",
        SubParallelSessions: "",
        ST: "",
        Name: "",
        Phone: "",
        VerifyVode: "",
        Company: "",
        Post: "",
        CertificateType: "",
        CertificateTypeEnum: "",
        IDCard: "",
        HeadImage: "",
        UnionId: "",
        Number: "",
        IsMatchMaking: true
      },
      certificateList: [
        { text: "身份证", value: "IDCard" },
        { text: "港澳台证", value: "HongKongMacaoAndTaiwan" },
        { text: "护照", value: "Passport" },
        { text: "军官证", value: "Armymen" }
      ]
    };
  },
  created() {
    var that = this;
    if (localStorage.getItem("userInfo")) {
      //查取localStorage
      this.userInfo = JSON.parse(localStorage.getItem("userInfo"));
      this.userInfo.VerifyVode = "";
    }
    if (this.$route.query.InviterUnionId) {
      //获取邀请人unionid
      this.userInfo.InviterUnionId = this.$route.query.InviterUnionId;
    }
    this.userInfo.UserAgent = window.navigator.userAgent; //获取设备信息
    // console.log(this.userInfo.UserAgent)
    this.userInfo.ST = this.$route.query.st; //获取活动号
    if (this.$route.query.number && this.$route.query.number != "") {
      //是否存在门票码
      this.userInfo.Number = this.$route.query.number;
      axios({
        method: "GET",
        url:
          that.baseUrl +
          "/api/user/selectNumber/" +
          that.$route.query.st +
          "/" +
          that.$route.query.number
      })
        .then(res => {
          that.userInfo.ST = res.data.ST;
          that.userInfo.Name = res.data.Name;
          that.userInfo.Phone = res.data.Phone;
          that.phone = res.data.Phone;
          that.userInfo.Company = res.data.Company;
          that.userInfo.Post = res.data.Post;
          that.userInfo.CertificateType =
            that.certificateList[res.data.CertificateTypeEnum].text;
          that.userInfo.CertificateTypeEnum = res.data.CertificateTypeEnum;
          that.userInfo.IDCard = res.data.IDCard;
          that.userInfo.HeadImage = res.data.HeadImage;
        })
        .catch(err => {
          console.log(err);
        });
    } else {
      if (this.$route.query.phone && this.$route.query.phone != "") {
        //是否存在手机号
        axios({
          method: "GET",
          url:
            that.baseUrl +
            "/api/user/checkphone/" +
            that.$route.query.st +
            "/" +
            that.$route.query.phone
        })
          .then(res => {
            if (res.data.State) {
              that.$dialog
                .confirm({
                  message: "您的信息已存在，是否查看电子票",
                  confirmButtonText: "去查票"
                })
                .then(() => {
                  window.location.href =
                    that.baseUrl +
                    "/Q/" +
                    that.userInfo.ST +
                    "/true?phone=" +
                    that.$route.query.phone;
                })
                .catch(() => {});
            } else {
              that.userInfo.Phone = that.$route.query.phone;
            }
          })
          .catch(err => {
            console.log(err);
          });
      }
      if (this.$route.query.name) {
        //获取用户姓名
        this.userInfo.Name = this.$route.query.name;
      }
    }
    axios({
      url: that.baseUrl + "/api/exhibition/getCredit/" + that.$route.query.st,
      method: "GET"
    })
      .then(res => {
        that.credit = res.data;
      })
      .catch(err => {
        console.log(err);
      });
    if (this.$route.query.UnionId) {
      //获取用户unionid
      this.userInfo.UnionId = this.$route.query.UnionId;
    }
  },
  mounted() {
    var that = this;
    $.ajax({
      //浏览量数据统计api
      url: that.baseUrl + "/api/Activity/Pageview",
      type: "POST",
      data: {
        ST: that.userInfo.ST
      },
      success: function(res) {
        // console.log(res)
      }
    });
  },
  watch: {
    "userInfo.Phone": function(val, oldVal) {
      if (/^1[345678]\d{9}$/.test(val) && val != this.phone) {
        this.codeIsShow = true;
      } else {
        this.codeIsShow = false;
        this.userInfo.VerifyVode = "";
      }
    },
    "userInfo.Company": function(val, oldVal) {
      if (!this.isChecked && this.trims(val).length > 1) {
        this.companyPrompt(this.trims(val));
      } else {
        this.companyTips = [];
        this.isChecked = false;
      }
    }
  },
  methods: {
    getCompany(item) {
      this.isChecked = true;
      this.userInfo.Company = item.corpname;
    },
    companyPrompt(val) {
      var that = this;
      axios({
        method: "GET",
        url:
          "https://fapiao.yonyoucloud.com/taxinfo/autoComplete?mc=" +
          encodeURIComponent(val)
      })
        .then(res => {
          if (res.data.code === "0000" && res.data.datas != null) {
            if (res.data.datas.length > 5) {
              that.companyTips = res.data.datas.slice(0, 5);
            } else {
              that.companyTips = res.data.datas;
            }
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    previewImg(e) {
      e.stopPropagation();
      var imgSrc = [];
      imgSrc.push(this.userInfo.HeadImage);
      ImagePreview(imgSrc);
    },
    showFileModel() {
      this.fileModel = true;
    },
    fileToggle(state) {
      if (state) {
        this.fileModel = true;
      } else {
        this.fileModel = false;
      }
    },
    fileChange(e) {
      this.fileModel = false;
      let image = document.getElementById("img");
      this.clip(e, {
        resultObj: image,
        aspectRatio: 1
      });
    },
    getCode() {
      var that = this;
      if (/^1[345678]\d{9}$/.test(that.userInfo.Phone)) {
        axios({
          method: "GET",
          url:
            that.baseUrl +
            "/api/user/checkphone/" +
            that.$route.query.st +
            "/" +
            that.userInfo.Phone
        })
          .then(res => {
            if (res.data.State) {
              that.$toast("该手机号已经报名");
              setTimeout(() => {
                window.location.href =
                  that.baseUrl +
                  "/Q/" +
                  that.userInfo.ST +
                  "/true?phone=" +
                  that.userInfo.Phone;
              }, 3000);
            } else {
              that.btnDisabled = true;
              axios({
                method: "GET",
                url:
                  that.baseUrl +
                  "/api/user/getVerifyVode/" +
                  that.userInfo.Phone
              })
                .then(res => {
                  // console.log(res)
                  var second = 60;
                  that.btnText = "还剩" + second + "秒";
                  var timer = setInterval(() => {
                    second--;
                    if (second > 0) {
                      that.btnText = "还剩" + second + "秒";
                    } else {
                      clearInterval(timer);
                      that.btnDisabled = false;
                      that.btnText = "发送验证码";
                      second = 60;
                    }
                  }, 1000);
                })
                .catch(err => {
                  console.log(err);
                });
            }
          })
          .catch(err => {
            console.log(err);
          });
      } else {
        this.$toast("请输入正确的手机号");
      }
    },
    showCertiPicker() {
      this.certificatePicker = true;
    },
    certiTypePicker(item) {
      this.certificatePicker = false;
      this.userInfo.CertificateTypeEnum = item.value;
      this.userInfo.CertificateType = item.text;
    },
    editInfo() {
      var that = this;
      this.$toast.loading({
        mask: true,
        message: "正在提交中...",
        duration: 0
      });
      $.ajax({
        url: that.baseUrl + "/api/user/edit",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(that.userInfo),
        success: function(res) {
          that.$toast.clear();
          if (res.State) {
            localStorage.removeItem("userInfo");
            localStorage.setItem("userInfo", JSON.stringify(that.userInfo));
            that.$router.push({
              path: "list",
              query: { number: that.$route.query.number }
            });
          } else {
            that.$toast(res.Message);
          }
        }
      });
    },
    submitInfo() {
      var that = this;
      this.$toast.loading({
        mask: true,
        message: "正在提交中...",
        duration: 0
      });
      $.ajax({
        url: that.baseUrl + "/api/user/submit",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(that.userInfo),
        success: function(res) {
          that.$toast.clear();
          if (res.State) {
            that.userInfo.Number = res.Data;
            localStorage.removeItem("userInfo");
            localStorage.setItem("userInfo", JSON.stringify(that.userInfo));
            that.$router.push("list");
          } else {
            that.$toast(res.Message);
          }
        }
      });
    },
    submitForm() {
      if (this.trims(this.userInfo.Name) == "") {
        this.$toast("请输入真实姓名");
      } else if (this.trims(this.userInfo.Phone) == "") {
        this.$toast("请输入手机号");
      } else if (
        this.codeIsShow &&
        this.trims(this.userInfo.VerifyVode) == ""
      ) {
        this.$toast("请输入手机验证码");
      } else if (this.trims(this.userInfo.Company) == "") {
        this.$toast("请输入单位名称");
      } else if (
        this.userInfo.ST != "dmz1017" &&
        this.trims(this.userInfo.Post) == ""
      ) {
        this.$toast("请输入职务");
      } else if (this.userInfo.ST != "dmz1017" && this.certificateType == "") {
        this.$toast("请选择证件类别");
      } else if (
        this.userInfo.ST != "dmz1017" &&
        this.trims(this.userInfo.IDCard) == ""
      ) {
        this.$toast("请输入证件号");
      } else if (
        this.userInfo.CertificateTypeEnum == "IDCard" &&
        /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/.test(
          this.trims(this.userInfo.IDCard)
        ) == false
      ) {
        this.$toast("身份证输入有误");
      } else if (
        this.userInfo.ST != "dmz1017" &&
        this.userInfo.HeadImage == ""
      ) {
        this.$toast("请先上传头像");
      } else {
        var that = this;
        if (this.$route.query.number && this.$route.query.number != "") {
          this.userInfo.VerifyVode = "0000";
          this.editInfo();
        } else {
          this.submitInfo();
        }
      }
    }
  }
};
</script>

<style>
@import "../assets/css/common.css";
@import "../assets/css/clipper.css";
.vue-container .van-radio .van-icon-checked {
  color: #37acff;
}

.vue-container .van-radio-group {
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.vue-container .van-radio {
  margin-left: 6.266vw;
  font-size: 4.266vw;
  color: #4d4d4d;
}
.match-making {
  border-bottom: 1px solid #eee;
}
.match-making .van-cell__title {
  text-align: left;
}
</style>
